package com.ihrm.system.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ihrm.common.entity.Constants;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.RolePermission;
import com.ihrm.domain.system.UserRole;
import com.ihrm.system.dao.RoleDao;
import com.ihrm.system.dao.RolePermissionDao;
import com.ihrm.system.dao.UserRoleDao;
import com.ihrm.system.service.RolePermissionService;
import com.ihrm.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private RolePermissionDao rolePermissionDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public Role getRoleById(String id) {
        Role role = roleDao.getById(id);
        List<RolePermission> list = rolePermissionDao.selectByRoleId(id);
        List<String> permIds = new ArrayList<>();
        list.forEach(item -> permIds.add(item.getPermissionId()));
        role.setPermIds(permIds);
        return role;
    }

    @Override
    public PageResult pageFind(Integer page, Integer pagesize, Role role) {
        PageHelper.startPage(page, pagesize);
        Page<Role> page1 = roleDao.pageFind(role);
        PageResult pageResult = PageResult.builder().total(page1.getTotal()).rows(page1.getResult()).build();
        return pageResult;
    }

    @Override
    public Integer updateRole(Role role) {
        return roleDao.update(role);
    }

    @Override
    public Integer delRoleById(String id) {
        List<UserRole> list = userRoleDao.getByRoleId(id);
        if(list.size() > 0) {
            throw new CommonException(Constants.FAIL_CODE, "不能删除已分配给用户的角色");
        }
        return roleDao.del(id);
    }

    @Override
    public Integer insert(Role role) {
        role.setId(new IdWorker().nextId() + "");
        return roleDao.insert(role);
    }

    @Override
    public List<Role> findAll(Role role) {
        return roleDao.findAll(role);
    }

    @Override
    public void assignPerms(Map<String, Object> map) {
        rolePermissionService.update(map);
    }
}
